<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequestFn"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDFH4btue7JFuIPHrACyThecLnzuYv1qPh',
  SecretKey: '3qLaYFfpjMipfEXZLq40h7G8k59wSigN'
})

export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    // 往后台上传成功后的回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 自定义图片上传过程
    httpRequestFn(res) {
      this.imageUrl = URL.createObjectURL(res.file) // 前端头像预览
      // 上传到云存储
      cos.putObject(
        {
          Bucket: 'yangkai-1309369797' /* 必须 */,
          Region: 'ap-beijing' /* 存储桶所在地域，必须字段 */,
          Key: res.file.name /* 必须 */,
          StorageClass: 'STANDARD', // 上传模式,标准模式
          Body: res.file, // 上传文件对象
          onProgress: function(progressData) {
            console.log(JSON.stringify(progressData))
          }
        },
        function(err, data) {
          console.log(err || data)
        }
      )
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
